package com.steven.ourcontest.team.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.steven.ourcontest.R
import com.steven.ourcontest.base.BaseActivity
import com.steven.ourcontest.team.adapter.MatchAdapter
import com.steven.ourcontest.team.viewmodel.AddTeamViewModel
import com.steven.ourcontest.utils.changed
import com.steven.ourcontest.utils.toast
import kotlinx.android.synthetic.main.activity_add_team.*

class AddTeamActivity : BaseActivity() {

    private val addTeamViewModel: AddTeamViewModel by viewModels()
    private val adapter = MatchAdapter(this) { id, name ->
        needLoad = false
        matchId = id
        et_match?.setText(name)
        fl_recycler_container?.isVisible = false
    }

    private var needLoad = true
    private var matchId = 0L
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getStatusBarColor(): Int {
        return R.color.white
    }

    override fun getViewId(): Int? {
        return R.layout.activity_add_team
    }

    override fun initView() {
        et_match?.changed {
            if (!it.isNullOrEmpty() && needLoad) {
                addTeamViewModel.editChange(it.toString())
                adapter.listData.clear()
            }
        }
        et_match?.setOnClickListener {
            needLoad = true
        }
        rv_match_list?.adapter = adapter
        addTeamViewModel.matchResponse.observe(this, Observer {
            adapter.listData.addAll(it.data)
            adapter.notifyDataSetChanged()
            fl_recycler_container?.isVisible = adapter.listData.isNotEmpty()
        })
        fl_recycler_container?.setEnableRefresh(false)
        fl_recycler_container?.setRefreshFooter(ClassicsFooter(this))
        fl_recycler_container?.setEnableAutoLoadMore(false)
        fl_recycler_container?.setOnLoadMoreListener {
            addTeamViewModel.queryMatchMore(et_match?.text.toString()) {
                fl_recycler_container?.finishLoadMore()
            }
        }
        tv_confirm?.setOnClickListener {
            val teamName = et_name?.text
            val matchName = et_match?.text
            var url = et_url?.text.toString()
            if (teamName.isNullOrEmpty()) {
                toast("请输入团队名称！")
                return@setOnClickListener
            }
            if (matchName.isNullOrEmpty()) {
                toast("请输入比赛名称！")
                return@setOnClickListener
            }
            if (url.isEmpty() || url == "null") {
                url = "无"
            }
            addTeamViewModel.createTeam(teamName.toString(), matchId, matchName.toString(), url) {
                toast("创建成功！")
                finish()
            }
        }
    }
}